package proxy.jdk_proxy;

import sun.misc.ProxyGenerator;

import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;

import proxy.Animal;
import proxy.Cat;

/**
 * 动态代理client，生成代理对象
 */
public class ProxyClient {

    private Animal animal;

    public void execute() throws IOException {
        //生成代理对象--被代理对象没有实现
//        Class<Animal> animalClass = Animal.class;
//        Animal animal1 = (Animal) Proxy.newProxyInstance(Animal.class.getClassLoader(), new Class[]{animalClass}, new ProxyHandler(animal));

        //2.被代理对象有实现
        Animal animal = new Cat();
        Class<?>[] interfaces = animal.getClass().getInterfaces();
        Animal animal1 = (Animal) Proxy.newProxyInstance(Animal.class.getClassLoader(), interfaces, new ProxyHandler(animal));

        //设置为true,会在工程根目录生成$Proxy0.class代理类（com.sun.proxy.$Proxy0.class）
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");


        byte[] bytes = ProxyGenerator.generateProxyClass("AnimalWithWithExtend$proxy", new Class[]{Animal.class});
        //放在根目录
        Path path = new File("./AnimalWithWithExtend$proxy.class").toPath();
        Files.write(path, bytes);
        animal1.eat();
    }
}
